package gonz.data.swim;


import gonz.common.Config;
import gonz.common.PriceAndArticleParser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.ArrayList;
import java.util.List;

public class Top {
    public static final Logger log = Logger.getLogger(Top.class);

    public static final String[] PRICE_ARTICLE_XPATHS = new String[]{
            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[4]",
            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[5]",
            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[4]",
            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[2]",
            "//div[@id='content']/div/div[2]/div[2]/div[2]/div[2]/div/p[3]",
            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[3]",
            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[5]",
            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[7]",
            "//div[@id='content']/div/div[2]/div[2]/div/div[2]/div/p[6]"};
    public static final String CONTAINER_IMAGES_XPATH = "//div[@id='swatchContainer0']/div";
    public static final String ALT_IMAGES_XPATH = "//div[@id='altImages']/div/a";
    public static final String MAIN_IMAGE_ID = "vsImage";
    public static final String UNKNOWN_PRICES_AND_ARTICLE_SYMBOL = "";
    private WebDriver webDriver;

    private String solidsPrice;
    private String printsPrice;
    private String price;
    private String origPrice;
    private String salePrice;
    private String specialPrice;
    private String clearancePrice;
    private String article;
    private Swim swim;
    private String imgFolder;
    private List<Image> images = new ArrayList<Image>();

    public Top(WebDriver webDriver, Swim swim, String imgFolder) {

        this.webDriver = webDriver;
        this.swim = swim;
        this.imgFolder = imgFolder;
        String pricesAndArticle = grabPricesAndArticle();
        this.solidsPrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_SOLIDS_ID);
        this.printsPrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_PRINTS_ID);
        this.price = PriceAndArticleParser.parsePrice(pricesAndArticle);
        this.origPrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_ORIG_ID);
        this.salePrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_SALE_ID);
        this.specialPrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_SPECIAL_ID);
        this.clearancePrice = PriceAndArticleParser.parsePrice(pricesAndArticle, PriceAndArticleParser.PRICE_CLEARANCE_ID);
        this.article = PriceAndArticleParser.parseArticle(pricesAndArticle);
        if (!isPriceExists()) {
            this.price = PriceAndArticleParser.parseAllPrices(pricesAndArticle);
            if (this.price.equalsIgnoreCase(PriceAndArticleParser.UNKNOWN_SYMBOL))
                log.error("Price for Top not found. " + webDriver.getCurrentUrl());
        }
        List<Image> containerImgs = grabContainerImages();

        if (containerImgs.size() == 0) {
            this.images.addAll(grabAlternateImages(false, 1));
        } else {
            this.images.addAll(containerImgs);
//            this.images.addAll(grabAlternateImages("images", true));
        }

        if (!Config.settings.getBoolean(Config.SKIP_ALTERNATE_KEY, true)) {
            this.images.addAll(grabAlternateImages(true, Integer.MAX_VALUE));
        }

        if (this.images.size() == 0) {
            Image mainImage = grabMainImage();
            if (mainImage == null)
                log.error("Image not found. swim link: " + getSwim().getLink());
            else
                this.images.add(mainImage);

        }

    }

    public Swim getSwim() {
        return swim;
    }

    public String getSolidsPrice() {
        return solidsPrice;
    }

    public String getPrintsPrice() {
        return printsPrice;
    }

    public String getPrice() {
        return price;
    }

    public String getOrigPrice() {
        return origPrice;
    }

    public String getSalePrice() {
        return salePrice;
    }

    public String getSpecialPrice() {
        return specialPrice;
    }

    public String getClearancePrice() {
        return clearancePrice;
    }

    public String getArticle() {
        return article;
    }

    public List<Image> getImages() {
        return images;
    }

    private String grabPricesAndArticle() {

        for (int i = 0; i < PRICE_ARTICLE_XPATHS.length; i++) {
            try {
                WebElement element = webDriver.findElement(By.xpath(PRICE_ARTICLE_XPATHS[i]));
//                element.sendKeys();
                if (element == null || element.getText().isEmpty())
                    log.debug("Can't find top price and article element: " + PRICE_ARTICLE_XPATHS[i]);
                else {
                    if (PriceAndArticleParser.isArticleExist(element.getText())) {
                        log.debug("TwoPiecesSwim top prices and article has been grabbed: " + PRICE_ARTICLE_XPATHS[i]);
                        return element.getText();
                    }
                }
            } catch (NoSuchElementException e) {
                log.debug("Can't find top price and article element: " + PRICE_ARTICLE_XPATHS[i]);
            }

        }
        log.error("Can't grab Top prices and article. " + webDriver.getCurrentUrl());
        return UNKNOWN_PRICES_AND_ARTICLE_SYMBOL;
    }

    private boolean isPriceExists() {
        return !(PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getPrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getPrintsPrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getSolidsPrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getSalePrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getOrigPrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getClearancePrice())
                && PriceAndArticleParser.UNKNOWN_SYMBOL.equalsIgnoreCase(getSpecialPrice()));
    }

    private List<Image> grabContainerImages() {
        List<Image> images = new ArrayList<Image>();
        List<WebElement> imagesDivElements = webDriver.findElements(By.xpath(CONTAINER_IMAGES_XPATH));
        if (imagesDivElements == null || imagesDivElements.size() == 0) {
            log.warn("There is no images in container. Skip." + " , swim link: " + getSwim().getLink());
            return images;
        }
        for (int j = 0; j < imagesDivElements.size(); j++) {
            String onclickAttr = imagesDivElements.get(j).getAttribute("onclick");
            if (StringUtils.isBlank(onclickAttr)) {
                log.warn("Can't find image link in container. Skip. N: " + j + " onclickAttr: " + onclickAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            String imageLink = StringUtils.substringBetween(onclickAttr, "'http://", "'");
            if (StringUtils.isBlank(imageLink)) {
                log.error("Can't parse image link in container. Skip. N: " + j + " onclickAttr: " + onclickAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            imageLink = "http://" + imageLink;
            Image image = new Image(imageLink, this);

            String onmouseoverAttr = imagesDivElements.get(j).getAttribute("onmouseover");
            String color;
            if (StringUtils.isBlank(onmouseoverAttr)) {
                log.warn("Can't find color in container. Using N. N: " + j + " onmouseoverAttr: " + onmouseoverAttr + " , swim link: " + getSwim().getLink());
                color = String.valueOf(j);
            } else {
                color = StringUtils.substringBetween(onmouseoverAttr, "'");
            }
            image.setColor(color);
            image.download(imgFolder);
            images.add(image);
        }

        return images;
    }

    private List<Image> grabAlternateImages(boolean skipFirst, int num) {
        List<Image> images = new ArrayList<Image>();
        int startFrom;
        if (skipFirst)
            startFrom = 1;
        else
            startFrom = 0;
        List<WebElement> imageElements = webDriver.findElements(By.xpath(ALT_IMAGES_XPATH));
        if (imageElements == null || imageElements.size() == 0) {
            log.warn("There is no alternate images. Skip. " + " , swim link: " + getSwim().getLink());
            return images;
        }

        if (imageElements.size() < num)
            num = imageElements.size();
        for (int j = startFrom; j < num; j++) {
            String hrefAttr = imageElements.get(j).getAttribute("href");
            if (StringUtils.isBlank(hrefAttr)) {
                log.warn("Can't find alternate image link. Skip. N: " + j + " hrefAttr: " + hrefAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            String imageLink = hrefAttr;
            if (StringUtils.isBlank(imageLink)) {
                log.error("Can't parse alternate image link. Skip. N: " + j + " hrefAttr: " + hrefAttr + " , swim link: " + getSwim().getLink());
                continue;
            }
            Image image = new Image(imageLink, this);
            image.setColor("alternate " + j);
            image.download(imgFolder);
            images.add(image);
        }
        return images;
    }

    private Image grabMainImage() {
        try {
            WebElement imageElement = webDriver.findElement(By.id(MAIN_IMAGE_ID));
            if (imageElement == null) {
                log.error("Main image not found , swim link: " + getSwim().getLink());
                return null;
            }
            String srcAttr = imageElement.getAttribute("src");
            if (StringUtils.isBlank(srcAttr))
                log.error("Cant find Main image link, srcAttr: " + srcAttr + " , swim link: " + getSwim().getLink());
            Image image = new Image(srcAttr, this);
            image.setColor("main");
            image.download(imgFolder);
            return image;
        } catch (NoSuchElementException e) {
            log.error("Main image not found , swim link: " + getSwim().getLink());
            return null;
        }


    }

}